/*
 * @Author: zxc
 * @Date: 2020-11-17 09:09:05
 * @LastEditTime: 2020-11-17 10:13:57
 * @LastEditors: zxc
 * @Description:职责链模式
 */

/**
 * @Author: zxc
 * @Date: 2020-11-17 09:21:32
 * @func 订单价格demo
 */

let order500 = function (orderType, pay, stock) {
  if (orderType === 1 && pay) {
    console.log("500订金，得100券一张")
  } else {
    return "nextSuccessor"
  }
}

let order200 = function (orderType, pay, stock) {
  if (orderType === 2 && pay) {
    console.log("200订金，得50券一张")
  } else {
    return "nextSuccessor"
  }
}

let orderNormal = function (orderType, pay, stock) {
  if (stock > 0) {
    console.log("普通购买，啥也不是")
  } else {
    console.log("没库存惹")
  }
}

// class Chain {
//   constructor(fn) {
//     this.fn = fn
//     this.successor = null
//   }
//   setNextSuccessor(successor) {
//     this.successor = successor
//   }
//   passRequest(...args) {
//     let ret = this.fn.apply(this, args)
//     if (ret === "nextSuccessor") {
//       return (
//         this.successor && this.successor.passRequest.apply(this.successor, args)
//       )
//     }
//     return ret
//   }
//   next(...args) {
//     return (
//       this.successor && thiss.successor.passRequest.apply(this.successor, args)
//     )
//   }
// }

// let chainOrder500 = new Chain(order500)
// let chainOrder200 = new Chain(order200)
// let chainOrderNormal = new Chain(orderNormal)

// chainOrder500.setNextSuccessor(chainOrder200)
// chainOrder200.setNextSuccessor(chainOrderNormal)

// chainOrder500.passRequest(1, true, 500)
// chainOrder500.passRequest(2, true, 500)
// chainOrder500.passRequest(3, true, 500)
// chainOrder500.passRequest(1, false, 0)

Function.prototype.after = function (fn) {
  let self = this
  return function (...args) {
    let ret = self.apply(this, args)
    if (ret === "nextSuccessor") {
      return fn.apply(this, args)
    }
    return ret
  }
}
let order = order500.after(order200).after(orderNormal)
order(1, true, 500)
order(2, true, 500)
order(1, false, 500)
